<!DOCTYPE html>
<html lang="zh-CN">
    <head>
    <meta charset="utf-8">

    

    <!-- 渲染优化 -->
    <meta name="renderer" content="webkit">
    <meta name="force-rendering" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1">
    <meta name="HandheldFriendly" content="True" >
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">

    <!--icon-->

    
        <link rel="shortcut icon" href="https://s1.imgpp.com/2022/01/28/owl.png">
    
    
    
    
    


    <!-- meta -->


<title>vue知识铺垫 | 猫头鹰的BLOG</title>


    <meta name="keywords" content="Es6模块化, promise, async/await, EventLoop, 宏任务和微任务, 猫头鹰的博客">




    <!-- OpenGraph -->
 
    <meta name="description" content="Es6模块化 三个定义：每个js文件都是一个模块import可以导入其他模块export可以向外共享  准备 安装&amp;#x6e;&amp;#111;&amp;#100;&amp;#x65;&amp;#x2e;&amp;#106;&amp;#x73;&amp;#x40;&amp;#x31;&amp;#52;&amp;#x2e;&amp;#x31;&amp;#x35;&amp;#x2e;&amp;#x31;版本或以上 npm init -y，快速创建一个包管理配置文件package.json 再package.j">
<meta property="og:type" content="article">
<meta property="og:title" content="vue知识铺垫">
<meta property="og:url" content="http://example.com/2022/03/17/vue%E7%9F%A5%E8%AF%86%E9%93%BA%E5%9E%AB/index.html">
<meta property="og:site_name" content="猫头鹰的BLOG">
<meta property="og:description" content="Es6模块化 三个定义：每个js文件都是一个模块import可以导入其他模块export可以向外共享  准备 安装&amp;#x6e;&amp;#111;&amp;#100;&amp;#x65;&amp;#x2e;&amp;#106;&amp;#x73;&amp;#x40;&amp;#x31;&amp;#52;&amp;#x2e;&amp;#x31;&amp;#x35;&amp;#x2e;&amp;#x31;版本或以上 npm init -y，快速创建一个包管理配置文件package.json 再package.j">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://images.pexels.com/photos/10643872/pexels-photo-10643872.jpeg?cs=srgb&dl=pexels-stijn-dijkstra-10643872.jpg&fm=jpg">
<meta property="article:published_time" content="2022-03-17T02:00:20.000Z">
<meta property="article:modified_time" content="2022-03-20T11:02:52.635Z">
<meta property="article:author" content="张程">
<meta property="article:tag" content="Es6模块化">
<meta property="article:tag" content="promise">
<meta property="article:tag" content="async&#x2F;await">
<meta property="article:tag" content="EventLoop">
<meta property="article:tag" content="宏任务和微任务">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:image" content="https://images.pexels.com/photos/10643872/pexels-photo-10643872.jpeg?cs=srgb&dl=pexels-stijn-dijkstra-10643872.jpg&fm=jpg">


    
<link rel="stylesheet" href="/css/style/main.css">
 

    
    
    
        <link rel="stylesheet" id="hl-default-theme" href="https://cdn.jsdelivr.net/npm/highlight.js@10.1.2/styles/arduino-light.min.css" media="none" >
        
            <link rel="stylesheet" id="hl-dark-theme" href="https://cdn.jsdelivr.net/npm/highlight.js@10.1.2/styles/obsidian.min.css" media="none">
        
    

    

    
    
<link rel="stylesheet" href="/css/style/dark.css">

    
<script src="/js/darkmode.js"></script>



     
    <script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
 

    <!-- custom head -->

<meta name="generator" content="Hexo 6.0.0"></head>

    <body>
        <div id="app">
            <header class="header">
    <div class="header__left">
        <a href="/" class="button">
            <span class="logo__text">猫头鹰</span>
        </a>
    </div>
    <div class="header__right">
        
            <div class="navbar__menus">
                
                    <a href="/" class="navbar-menu button">首页</a>
                
                    <a href="/tags/" class="navbar-menu button">标签</a>
                
                    <a href="/categories/" class="navbar-menu button">分类</a>
                
                    <a href="/archives/" class="navbar-menu button">归档</a>
                
            </div>
        
        
        
    <a href="/search/" id="btn-search">
        <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1024 1024" width="24" height="24" fill="currentColor" stroke="currentColor" stroke-width="32"><path d="M192 448c0-141.152 114.848-256 256-256s256 114.848 256 256-114.848 256-256 256-256-114.848-256-256z m710.624 409.376l-206.88-206.88A318.784 318.784 0 0 0 768 448c0-176.736-143.264-320-320-320S128 271.264 128 448s143.264 320 320 320a318.784 318.784 0 0 0 202.496-72.256l206.88 206.88 45.248-45.248z"></path></svg>
    </a>


        
        
    <a href="javaScript:void(0);" id="btn-toggle-dark">
        <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"></path></svg>
    </a>


        
            <a class="dropdown-icon button" id="btn-dropdown" tabindex="0"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" width='24' height='24' fill="none" stroke="currentColor" stroke-width="0.7" stroke-linecap="round" stroke-linejoin="round"><path fill="currentColor" d="M3.314,4.8h13.372c0.41,0,0.743-0.333,0.743-0.743c0-0.41-0.333-0.743-0.743-0.743H3.314c-0.41,0-0.743,0.333-0.743,0.743C2.571,4.467,2.904,4.8,3.314,4.8z M16.686,15.2H3.314c-0.41,0-0.743,0.333-0.743,0.743s0.333,0.743,0.743,0.743h13.372c0.41,0,0.743-0.333,0.743-0.743S17.096,15.2,16.686,15.2z M16.686,9.257H3.314c-0.41,0-0.743,0.333-0.743,0.743s0.333,0.743,0.743,0.743h13.372c0.41,0,0.743-0.333,0.743-0.743S17.096,9.257,16.686,9.257z"></path></svg></a>
            <div class="dropdown-menus" id="dropdown-menus">
                
                    <a href="/" class="dropdown-menu button">首页</a>
                
                    <a href="/tags/" class="dropdown-menu button">标签</a>
                
                    <a href="/categories/" class="dropdown-menu button">分类</a>
                
                    <a href="/archives/" class="dropdown-menu button">归档</a>
                
            </div>
        
    </div>
</header>


            <main class="main">
    

<div class="post-title">
    <h1 class="post-title__text">
        vue知识铺垫
    </h1>
    <div class="post-title__meta">
        <a href="/archives/2022/03/" class="post-meta__date button">2022-03-17</a>
        
    <span class="separate-dot"></span><a href="/categories/vue2/" class="button">vue2</a>

 
        
    
     
    <span id="busuanzi_container_page_pv" hidden>
        <span class="separate-dot"></span>
        <span></span>
        <span id="busuanzi_value_page_pv"></span>
        <span>次观看</span>
    </span>



 

 
    </div>
</div>



<article class="post content-card">
    <div class="post__header">
    
        <div class="post-thumbnail lazy" data-bg="https://images.pexels.com/photos/10643872/pexels-photo-10643872.jpeg?cs=srgb&amp;dl=pexels-stijn-dijkstra-10643872.jpg&amp;fm=jpg"></div>
    
</div>
    <div class="post__content">
        <h2 id="Es6模块化"><a href="#Es6模块化" class="headerlink" title="Es6模块化"></a>Es6模块化</h2><blockquote>
<p>三个定义：<br>每个js文件都是一个模块<br>import可以导入其他模块<br>export可以向外共享</p>
</blockquote>
<h4 id="准备"><a href="#准备" class="headerlink" title="准备"></a>准备</h4><ol>
<li>安装<a href="mailto:&#x6e;&#111;&#100;&#x65;&#x2e;&#106;&#x73;&#x40;&#x31;&#52;&#x2e;&#x31;&#x35;&#x2e;&#x31;">&#x6e;&#111;&#100;&#x65;&#x2e;&#106;&#x73;&#x40;&#x31;&#52;&#x2e;&#x31;&#x35;&#x2e;&#x31;</a>版本或以上</li>
<li>npm init -y，快速创建一个包管理配置文件package.json</li>
<li>再package.json中添加配置项：”type”:”module”</li>
</ol>
<h4 id="默认导出-导入"><a href="#默认导出-导入" class="headerlink" title="默认导出/导入"></a>默认导出/导入</h4><pre><code class="hljs javascript"><span class="hljs-keyword">let</span> n1 = <span class="hljs-number">10</span>
<span class="hljs-keyword">let</span> n2 = <span class="hljs-number">20</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">show</span>(<span class="hljs-params"></span>) </span>&#123;&#125;
<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> &#123;
    n2,
    show
&#125;</code></pre>

<pre><code class="hljs javascript"><span class="hljs-keyword">import</span> module1 <span class="hljs-keyword">from</span> <span class="hljs-string">&quot;./01默认导出.js&quot;</span>
<span class="hljs-built_in">console</span>.log(module1);</code></pre>

<h4 id="按需导入-导出"><a href="#按需导入-导出" class="headerlink" title="按需导入/导出"></a>按需导入/导出</h4><pre><code class="hljs javascript"><span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> &#123;
	a=<span class="hljs-number">20</span>
&#125;
<span class="hljs-keyword">export</span> <span class="hljs-keyword">let</span> n1=<span class="hljs-number">10</span>
<span class="hljs-keyword">export</span> <span class="hljs-keyword">let</span> n2=<span class="hljs-number">20</span>
<span class="hljs-keyword">export</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">show</span>(<span class="hljs-params"></span>)</span>&#123;&#125;</code></pre>

<pre><code class="hljs javascript"><span class="hljs-keyword">import</span> info, &#123;n1 <span class="hljs-keyword">as</span> s1,n2 <span class="hljs-keyword">as</span> s2,show&#125; <span class="hljs-keyword">from</span> <span class="hljs-string">&quot;./03按需导出.js&quot;</span></code></pre>

<blockquote>
<p>注意事项<br>每个模块中可以多次使用按需导出<br>按需导入/导出的成员名称应相同<br>as 对按需导入的关键字重命名<br>默认导入可以和默认到处一起用</p>
</blockquote>
<h4 id="直接导入并执行模块中的代码"><a href="#直接导入并执行模块中的代码" class="headerlink" title="直接导入并执行模块中的代码"></a>直接导入并执行模块中的代码</h4><pre><code class="hljs javascript"><span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">10</span>; i++)&#123;
    <span class="hljs-built_in">console</span>.log(i);
&#125;</code></pre>

<pre><code class="hljs javascript"><span class="hljs-keyword">import</span> <span class="hljs-string">&quot;./05直接运行模块中代码块.js&quot;</span></code></pre>

<blockquote>
<p>注意：只能直接导入代码块，而不是成员属性和方法</p>
</blockquote>
<h2 id="Promise"><a href="#Promise" class="headerlink" title="Promise"></a>Promise</h2><blockquote>
<p>用于解决回调地狱问题<br>地狱问题:多个回调函数进行嵌套，形成回调地狱<br>Promise:是一个构造函数，可以创建一个实例化对象(代表一个异步操作)</p>
</blockquote>
<h4 id="读取文件内容案例"><a href="#读取文件内容案例" class="headerlink" title="读取文件内容案例"></a>读取文件内容案例</h4><blockquote>
<p>准备<br>因为node.js提供的fs模块仅支持以回调函数的形式读取文件，不支持Promise的调用方式，所以使用第三方包then-Fs<br>npm i then-fs<br>import thenFs from “then=fs”</p>
</blockquote>
<h4 id="then"><a href="#then" class="headerlink" title="then()"></a>then()</h4><blockquote>
<p>是Promise原型对象上的一个方法：Promise.prototype.then()<br>then(成功时的回调函数，失败时的回调函数)<br>特性：如果上一个.then()方法返回的是一个Promise的实例化对象，则可以通过.then()继续处理，这是then方法的链式调用，从而解决回调地狱问题</p>
</blockquote>
<pre><code class="hljs javascript"><span class="hljs-keyword">import</span> thenFs <span class="hljs-keyword">from</span> <span class="hljs-string">&quot;then-fs&quot;</span>

thenFs.readFile(<span class="hljs-string">&quot;./files/11.txt&quot;</span>,<span class="hljs-string">&quot;utf-8&quot;</span>).then(<span class="hljs-function">(<span class="hljs-params">response</span>) =&gt;</span> &#123;
    <span class="hljs-built_in">console</span>.log(response);
&#125;,<span class="hljs-function">(<span class="hljs-params">err</span>)=&gt;</span>&#123;
	<span class="hljs-built_in">console</span>.log(err);
&#125;)</code></pre>


<h4 id="catch"><a href="#catch" class="headerlink" title="catch()"></a>catch()</h4><blockquote>
<p>是Promise原型对象上的一个方法：Promise.prototype.catch()<br>在Promise的异步操作中，能进行捕获和处理</p>
</blockquote>
<pre><code class="hljs javascript"><span class="hljs-keyword">import</span> thenFs <span class="hljs-keyword">from</span> <span class="hljs-string">&quot;then-fs&quot;</span>

thenFs.readFile(<span class="hljs-string">&quot;./files/11.txt&quot;</span>,<span class="hljs-string">&quot;utf-8&quot;</span>).then(<span class="hljs-function">(<span class="hljs-params">response</span>) =&gt;</span> &#123;
    <span class="hljs-built_in">console</span>.log(response);
    <span class="hljs-keyword">return</span> thenFs.readFile(<span class="hljs-string">&quot;./files/2.txt&quot;</span>,<span class="hljs-string">&quot;utf-8&quot;</span>)
&#125;).then(<span class="hljs-function">(<span class="hljs-params">response</span>) =&gt;</span> &#123;
    <span class="hljs-built_in">console</span>.log(response);
    <span class="hljs-keyword">return</span> thenFs.readFile(<span class="hljs-string">&quot;./files/3.txt&quot;</span>,<span class="hljs-string">&quot;utf-8&quot;</span>)
&#125;).then(<span class="hljs-function">(<span class="hljs-params">response</span>) =&gt;</span> &#123;
    <span class="hljs-built_in">console</span>.log(response);
&#125;).catch(<span class="hljs-function">(<span class="hljs-params">err</span>) =&gt;</span> &#123;
    <span class="hljs-built_in">console</span>.log(err);
&#125;)</code></pre>

<h4 id="all"><a href="#all" class="headerlink" title="all()"></a>all()</h4><blockquote>
<p>是Promise原型对象上的一个方法：Promise.prototype.all()<br>Promise.all()会发起并行的Promise异步操作，等所有异步操作执行完，才会进行.then()操作</p>
</blockquote>
<pre><code class="hljs javascript"><span class="hljs-keyword">import</span> thenFs <span class="hljs-keyword">from</span> <span class="hljs-string">&quot;then-fs&quot;</span>
<span class="hljs-built_in">Promise</span>.all([thenFs.readFile(<span class="hljs-string">&quot;./files/1.txt&quot;</span>, <span class="hljs-string">&#x27;utf-8&#x27;</span>), thenFs.readFile(<span class="hljs-string">&quot;./files/2.txt&quot;</span>, <span class="hljs-string">&#x27;utf-8&#x27;</span>), thenFs.readFile(<span class="hljs-string">&quot;./files/3.txt&quot;</span>, <span class="hljs-string">&#x27;utf-8&#x27;</span>)]).then(<span class="hljs-function">(<span class="hljs-params">[r1, r2, r3]</span>) =&gt;</span> &#123;
    <span class="hljs-built_in">console</span>.log(r1,r2,r3);
&#125;).catch(<span class="hljs-function">(<span class="hljs-params">err</span>) =&gt;</span> &#123;
    <span class="hljs-built_in">console</span>.log(err);
&#125;)</code></pre>

<h4 id="race"><a href="#race" class="headerlink" title="race()"></a>race()</h4><blockquote>
<p>是Promise原型对象上的一个方法：Promise.prototype.race()<br>Promise.race()会发起一个并行的Promise异步操作,只要任意一个异步操作完成，就会立即执行下一个.then()操作</p>
</blockquote>
<pre><code class="hljs javascript"><span class="hljs-keyword">import</span> thenFs <span class="hljs-keyword">from</span> <span class="hljs-string">&quot;then-fs&quot;</span>;
<span class="hljs-built_in">Promise</span>.race([thenFs.readFile(<span class="hljs-string">&quot;./files/1.txt&quot;</span>, <span class="hljs-string">&quot;utf-8&quot;</span>), thenFs.readFile(<span class="hljs-string">&quot;./files/2.txt&quot;</span>, <span class="hljs-string">&quot;utf-8&quot;</span>), thenFs.readFile(<span class="hljs-string">&quot;./files/3.txt&quot;</span>, <span class="hljs-string">&quot;utf-8&quot;</span>),]).then(<span class="hljs-function">(<span class="hljs-params">r1</span>)=&gt;</span> &#123;
    <span class="hljs-built_in">console</span>.log(r1);
&#125;).catch(<span class="hljs-function">(<span class="hljs-params">err</span>) =&gt;</span> &#123;
    <span class="hljs-built_in">console</span>.log(err);
&#125;)</code></pre>
<h4 id="基于Promise封装读文件方法"><a href="#基于Promise封装读文件方法" class="headerlink" title="基于Promise封装读文件方法"></a>基于Promise封装读文件方法</h4><blockquote>
<p>封装要求：<br>方法名：getFile<br>接收一个形参：fpath<br>返回值：Promise的实例化对象</p>
</blockquote>
<pre><code class="hljs javascript"><span class="hljs-keyword">import</span> &#123; rejects &#125; <span class="hljs-keyword">from</span> <span class="hljs-string">&quot;assert&quot;</span>;
<span class="hljs-keyword">import</span> fs <span class="hljs-keyword">from</span> <span class="hljs-string">&quot;fs&quot;</span>;
<span class="hljs-keyword">import</span> &#123; resolve &#125; <span class="hljs-keyword">from</span> <span class="hljs-string">&quot;path&quot;</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getFile</span>(<span class="hljs-params">fpath</span>) </span>&#123;
    <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">resolve,reject</span>) </span>&#123;
        fs.readFile(fpath, <span class="hljs-string">&#x27;utf-8&#x27;</span>, <span class="hljs-function">(<span class="hljs-params">err, response</span>) =&gt;</span> &#123;
            <span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">return</span> reject(err)
            resolve(response)
        &#125;)
    &#125;)
&#125;
getFile(<span class="hljs-string">&quot;./files/1.txt&quot;</span>).then(<span class="hljs-function">(<span class="hljs-params">response</span>) =&gt;</span> &#123;
    <span class="hljs-built_in">console</span>.log(response);
&#125;).catch(<span class="hljs-function">(<span class="hljs-params">err</span>) =&gt;</span> &#123;
    <span class="hljs-built_in">console</span>.log(err);
&#125;)</code></pre>

<h4 id="async和await"><a href="#async和await" class="headerlink" title="async和await"></a>async和await</h4><blockquote>
<p>用于简化Promise的异步操作<br>解决了回调地狱问题和.then()的链式调用<br>如果使用了await关键字，function一定要用async修饰<br>第一个await之前的代码时同步,之后的代码时异步</p>
</blockquote>
<pre><code class="hljs javascript"><span class="hljs-keyword">import</span> thenFs <span class="hljs-keyword">from</span> <span class="hljs-string">&quot;then-fs&quot;</span>;
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">&quot;a&quot;</span>);
<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getAllFile</span>(<span class="hljs-params"></span>) </span>&#123;
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">&quot;b&quot;</span>);
    <span class="hljs-comment">// 第一个await之前的代码时同步</span>
    <span class="hljs-comment">// 之后的代码时异步</span>
    <span class="hljs-keyword">let</span> r1 = <span class="hljs-keyword">await</span> thenFs.readFile(<span class="hljs-string">&quot;./files/1.txt&quot;</span>, <span class="hljs-string">&quot;utf-8&quot;</span>)
    <span class="hljs-keyword">let</span> r2 = <span class="hljs-keyword">await</span> thenFs.readFile(<span class="hljs-string">&quot;./files/2.txt&quot;</span>, <span class="hljs-string">&quot;utf-8&quot;</span>)
    <span class="hljs-keyword">let</span> r3 = <span class="hljs-keyword">await</span> thenFs.readFile(<span class="hljs-string">&quot;./files/3.txt&quot;</span>, <span class="hljs-string">&quot;utf-8&quot;</span>)
    <span class="hljs-built_in">console</span>.log(r1, r2, r3);
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">&quot;d&quot;</span>);
&#125;
getAllFile()
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">&quot;c&quot;</span>);</code></pre>

<h4 id="EventLoop"><a href="#EventLoop" class="headerlink" title="EventLoop"></a>EventLoop</h4><blockquote>
<p>javascript是单线程语言</p>
</blockquote>
<p><img src="https://imgpp.com/s1/2022/03/17/imageb881ccc263726ad3.png" class="lazy" data-srcset="https://imgpp.com/s1/2022/03/17/imageb881ccc263726ad3.png" srcset="" alt="EventLoop"></p>
<h4 id="同步任务-异步任务"><a href="#同步任务-异步任务" class="headerlink" title="同步任务/异步任务"></a>同步任务/异步任务</h4><blockquote>
<p>同步任务：非耗时任务，要排队<br>异步任务: 耗时任务，会由javascript委托给宿主环境(node.js或浏览器)执行</p>
</blockquote>
<p><img src="https://imgpp.com/s1/2022/03/17/image2a7ce73e3a9c4752.png" class="lazy" data-srcset="https://imgpp.com/s1/2022/03/17/image2a7ce73e3a9c4752.png" srcset="" alt="同步任务/异步任务"></p>
<p><img src="https://imgpp.com/s1/2022/03/17/imagebb13c304732cd4a3.png" class="lazy" data-srcset="https://imgpp.com/s1/2022/03/17/imagebb13c304732cd4a3.png" srcset="" alt="同步任务/异步任务"></p>
<blockquote>
<p>结果:ADCB</p>
</blockquote>
<h4 id="宏任务和微任务"><a href="#宏任务和微任务" class="headerlink" title="宏任务和微任务"></a>宏任务和微任务</h4><p><img src="https://imgpp.com/s1/2022/03/17/image837c426f4e18c203.png" class="lazy" data-srcset="https://imgpp.com/s1/2022/03/17/image837c426f4e18c203.png" srcset="" alt="宏任务和微任务"></p>
<p><img src="https://imgpp.com/s1/2022/03/17/image97e508bafaed7f30.png" class="lazy" data-srcset="https://imgpp.com/s1/2022/03/17/image97e508bafaed7f30.png" srcset="" alt="宏任务和微任务"></p>
<blockquote>
<p>结果:156234789</p>
</blockquote>
<h2 id="API接口案例"><a href="#API接口案例" class="headerlink" title="API接口案例"></a>API接口案例</h2><h4 id="所需技术"><a href="#所需技术" class="headerlink" title="所需技术"></a>所需技术</h4><ol>
<li>第三方包express和mysql</li>
<li>Es6模块化</li>
<li>Promise</li>
<li>async/await<h4 id="步骤"><a href="#步骤" class="headerlink" title="步骤"></a>步骤</h4></li>
<li>创建包管理配置文件： npm init -y</li>
<li>安装express：npm install express –save</li>
<li>配置es6模块化：”type”: “module”</li>
<li>创建项目结构:控制器目录，数据库目录，路由目录，入口文件</li>
<li>在入口文件中导入express,实例化一个express对象，调用listen方法，启动服务器并建立侦听连接<pre><code class="hljs javascript"><span class="hljs-keyword">import</span> express <span class="hljs-keyword">from</span> <span class="hljs-string">&quot;express&quot;</span>

<span class="hljs-keyword">const</span> app = <span class="hljs-keyword">new</span> express()
app.listen(<span class="hljs-number">80</span>, <span class="hljs-function">() =&gt;</span> &#123;
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">&quot;serve run at:http://127.0.0.1&quot;</span>);
&#125;)</code></pre></li>
<li>安装mysql2：npm install –save mysql2</li>
<li>在路由目录下新建js文件，导入mysql2，调用支持Promise的API:createPool方法实例化一个对象，连接数据库<pre><code class="hljs javascript"><span class="hljs-keyword">import</span> mysql <span class="hljs-keyword">from</span> <span class="hljs-string">&quot;mysql2&quot;</span>
<span class="hljs-keyword">const</span> pool = mysql.createPool(&#123;
    <span class="hljs-attr">host</span>: <span class="hljs-string">&#x27;127.0.0.1&#x27;</span>,
    <span class="hljs-attr">port</span>: <span class="hljs-string">&#x27;3306&#x27;</span>,
    <span class="hljs-attr">database</span>: <span class="hljs-string">&quot;mty_db_01&quot;</span>,
    <span class="hljs-attr">user</span>: <span class="hljs-string">&#x27;root&#x27;</span>,
    <span class="hljs-attr">password</span>:<span class="hljs-string">&#x27;root&#x27;</span>
&#125;)

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> pool.promise()</code></pre></li>
<li>在控制器目录下新建js文件,导入连接数据库的js文件，对数据库进行查询<pre><code class="hljs javascript"><span class="hljs-keyword">import</span> db <span class="hljs-keyword">from</span> <span class="hljs-string">&quot;../db/index.js&quot;</span>;

<span class="hljs-keyword">export</span> <span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getAllUser</span>(<span class="hljs-params">req, res</span>) </span>&#123;
  <span class="hljs-keyword">try</span> &#123;
    <span class="hljs-keyword">const</span> [rows] = <span class="hljs-keyword">await</span> db.query(<span class="hljs-string">&quot;select id,username,nickname from ev_users&quot;</span>);
    res.send(&#123;
      <span class="hljs-attr">status</span>: <span class="hljs-number">0</span>,
      <span class="hljs-attr">message</span>: <span class="hljs-string">&quot;获取用户信息成功！&quot;</span>,
      <span class="hljs-attr">data</span>: rows,
    &#125;);
  &#125; <span class="hljs-keyword">catch</span> (e) &#123;
    res.send(&#123;
      <span class="hljs-attr">status</span>: <span class="hljs-number">0</span>,
      <span class="hljs-attr">message</span>: <span class="hljs-string">&quot;获取用户信息失败！&quot;</span>,
      <span class="hljs-attr">data</span>: e.message,
    &#125;);
  &#125; 
&#125;</code></pre></li>
<li>在路由目录下新建js文件，导入express和控制器的js文件，调用Router(),建立路由<pre><code class="hljs javascript"><span class="hljs-keyword">import</span> express <span class="hljs-keyword">from</span> <span class="hljs-string">&quot;express&quot;</span>
<span class="hljs-keyword">import</span> &#123; getAllUser &#125; <span class="hljs-keyword">from</span> <span class="hljs-string">&quot;../controller/user_ctrl.js&quot;</span>

<span class="hljs-keyword">const</span> router = <span class="hljs-keyword">new</span> express.Router()
router.get(<span class="hljs-string">&#x27;/user&#x27;</span>, getAllUser)

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> router</code></pre></li>
<li>在入口文件中导入路由的js文件<pre><code class="hljs javascript"><span class="hljs-keyword">import</span> userRouter <span class="hljs-keyword">from</span> <span class="hljs-string">&quot;./router/user_router.js&quot;</span></code></pre></li>
<li>node app.js 启动服务器</li>
<li>在Postman中打开地址<a target="_blank" rel="noopener" href="http://127.0.0.1/api/user">http://127.0.0.1/api/user</a><br><img src="https://imgpp.com/s1/2022/03/20/image.png" class="lazy" data-srcset="https://imgpp.com/s1/2022/03/20/image.png" srcset="" alt="结果"><blockquote>
<p>-g全局<br>-S –save<br>-D –save-dev<br>-y不用打yes</p>
</blockquote>
</li>
</ol>

    </div>
     
    <div class="post-footer__meta"><p>更新于 2022-03-20</p></div> 
    <div class="post-entry__tags"><a href="/tags/Es6%E6%A8%A1%E5%9D%97%E5%8C%96/" class="post-tags__link button"># Es6模块化</a><a href="/tags/promise/" class="post-tags__link button"># promise</a><a href="/tags/async-await/" class="post-tags__link button"># async/await</a><a href="/tags/EventLoop/" class="post-tags__link button"># EventLoop</a><a href="/tags/%E5%AE%8F%E4%BB%BB%E5%8A%A1%E5%92%8C%E5%BE%AE%E4%BB%BB%E5%8A%A1/" class="post-tags__link button"># 宏任务和微任务</a></div> 
</article>


    <div class="nav">
        <div class="nav__prev">
            
                <a href="/2022/03/18/webpack%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/" class="nav__link">
                    <div>
                        <svg viewBox="0 0 1024 1024" xmlns="http://www.w3.org/2000/svg" width="24" height="24"><path d="M589.088 790.624L310.464 512l278.624-278.624 45.248 45.248L400.96 512l233.376 233.376z" fill="#808080"></path></svg>
                    </div>
                    <div>
                        <div class="nav__label">
                            <!-- Previous Post -->
                            上一页
                        </div>
                        <div class="nav__title">
                            webpack的使用
                        </div>
                    </div>
                </a>
            
        </div>
        <div class="nav__next">
            
                <a href="/2022/03/15/vue%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/" class="nav__link">
                    <div>
                        <div class="nav__label">
                            <!-- Next Post -->
                            下一页
                        </div>
                        <div class="nav__title">
                            vue2学习笔记
                        </div>
                    </div>
                    <div>
                        <svg viewBox="0 0 1024 1024" xmlns="http://www.w3.org/2000/svg" width="24" height="24"><path d="M434.944 790.624l-45.248-45.248L623.04 512l-233.376-233.376 45.248-45.248L713.568 512z" fill="#808080"></path></svg>
                    </div>
                </a>
            
        </div>
    </div>



    <div class="post__comments content-card" id="comment">
        
    <h4>评论</h4>
    
    
    
    <div id="valine_container" class="valine_thread"></div>

    
    
    
    
    
    
    
    


    </div>



</main>

            <footer class="footer" style="font-size: 10px;">
     
    <a href="#" class="button" id="b2t" aria-label="回到顶部" title="回到顶部">
        <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1024 1024" width="32" height="32">
            <path d="M233.376 722.752L278.624 768 512 534.624 745.376 768l45.248-45.248L512 444.128zM192 352h640V288H192z" fill="currentColor"></path>
        </svg>
    </a>

    


    
    
    
        <span id="busuanzi_container_site_uv" hidden>
            <span>游客:</span>
            <span id="busuanzi_value_site_uv"></span>
            <span></span>
            
                <span> </span>
            
        </span>
    
    
        <span id="busuanzi_container_site_pv" hidden>
            <span>次数:</span>
            <span id="busuanzi_value_site_pv"></span>
            <span></span>
            
        </span>
    
 
 

 
    
    
    <p>
        <!-- Powered by <a href="https://hexo.io" target="_blank">Hexo</a> | Theme - <a href="https://github.com/ChrAlpha/hexo-theme-cards" target="_blank">Cards</a> -->
        <span style="color: black;">作者：张程</span>
    </p>
    <script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js">
    </script>
    <script>
        var a_idx = 0;
            jQuery(document).ready(function($) {
                $("body").click(function(e) {
                    var a = new Array("会当凌绝顶，一览众山小", "春蚕到死丝方尽，蜡炬成灰泪始干", "夕阳无限好，只是近黄昏",
                     "位卑未敢忘忧国", "纸上得来终觉浅，绝知此事要躬行", "人生自古谁无死，留取丹心照汗青", "山重水复疑无路，柳暗花明又一村" ,
                     "小荷才露尖尖角，早有蜻蜓立上头", "床前明月光，疑是地上霜", "春色满园关不住，一枝红杏出墙来", 
                     "山际见来烟，竹中窥落日", "道狭草木长，夕露沾我衣","天长地久有时尽，此恨绵绵无绝期");
                    var color = new Array("#7B7B7B", "#CE0000", "#FF0080","#E800E8","#921AFF","#2828FF",
                    "#0072E3","#00CACA","#02DF82","#00DB00","#8CEA00","#E1E100","#EAC100","#F75000"
                    ,"#B87070","#AFAF61","#6FB7B7","#9999CC","#B766AD");
                    var $i = $("<a href='#' style='text-decoration:none'/>").text(a[a_idx]);
                    a_idx = (a_idx + 1) % a.length;
                    var x = e.pageX,
                        y = e.pageY;
                    $i.css({
                        "z-index": 999999999999999999999999999999999999999999999999999999999999999999999,
                        "top": y - 20,
                        "left": x,
                        "position": "absolute",
                        "font-weight": "bold",
                        "color": color[Math.floor(Math.random()*color.length)]
                    });
                    $("body").append($i);
                    $i.animate({
                            "top": y - 180,
                            "opacity": 0
                        },
                        1500,
                        function() {
                            $i.remove();
                        });
                });
            });
        </script>
    <script>
        !function() {
            function o(w, v, i) {
                return w.getAttribute(v) || i
            }
            function j(i) {
                return document.getElementsByTagName(i)
            }
            function l() {
                var i = j("script"),
                w = i.length,
                v = i[w - 1];
                return {
                    l: w,
                    z: o(v, "zIndex", -1),
                    o: o(v, "opacity", 0.5),
                    c: o(v, "color", "0,0,0"),
                    n: o(v, "count", 99)
                }
            }
            function k() {
                r = u.width = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth,
                n = u.height = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight
            }
            function b() {
                e.clearRect(0, 0, r, n);
                var w = [f].concat(t);
                var x, v, A, B, z, y;
                t.forEach(function(i) {
                    i.x += i.xa,
                    i.y += i.ya,
                    i.xa *= i.x > r || i.x < 0 ? -1 : 1,
                    i.ya *= i.y > n || i.y < 0 ? -1 : 1,
                    e.fillRect(i.x - 0.5, i.y - 0.5, 1, 1);
                    for (v = 0; v < w.length; v++) {
                        x = w[v];
                        if (i !== x && null !== x.x && null !== x.y) {
                            B = i.x - x.x,
                            z = i.y - x.y,
                            y = B * B + z * z;
                            y < x.max && (x === f && y >= x.max / 2 && (i.x -= 0.03 * B, i.y -= 0.03 * z), A = (x.max - y) / x.max, e.beginPath(), e.lineWidth = A / 2, e.strokeStyle = "rgba(" + s.c + "," + (A + 0.2) + ")", e.moveTo(i.x, i.y), e.lineTo(x.x, x.y), e.stroke())
                        }
                    }
                    w.splice(w.indexOf(i), 1)
                }),
                m(b)
            }
            var u = document.createElement("canvas"),
            s = l(),
            c = "c_n" + s.l,
            e = u.getContext("2d"),
            r,
            n,
            m = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame ||
            function(i) {
                window.setTimeout(i, 1000 / 45)
            },
            a = Math.random,
            f = {
                x: null,
                y: null,
                max: 20000
            };
            u.id = c;
            u.style.cssText = "position:fixed;top:0;left:0;z-index:" + s.z + ";opacity:" + s.o;
            j("body")[0].appendChild(u);
            k(),
            window.onresize = k;
            window.onmousemove = function(i) {
                i = i || window.event,
                f.x = i.clientX,
                f.y = i.clientY
            },
            window.onmouseout = function() {
                f.x = null,
                f.y = null
            };
            for (var t = [], p = 0; s.n > p; p++) {
                var h = a() * r,
                g = a() * n,
                q = 2 * a() - 1,
                d = 2 * a() - 1;
                t.push({
                    x: h,
                    y: g,
                    xa: q,
                    ya: d,
                    max: 6000
                })
            }
            setTimeout(function() {
                b()
            }, 100)
    } ();
    </script>
</footer>

        </div>
        
    <script defer src="https://cdn.jsdelivr.net/npm/vanilla-lazyload@17.1.0/dist/lazyload.min.js"></script>
    <script>
        window.lazyLoadOptions = {
            elements_selector: ".lazy",
            threshold: 0
        };
    </script>
 

 

 

 

 



 



 


    
 


    
<script src="https://cdn.jsdelivr.net/npm/jquery@3.4.1/dist/jquery.min.js"></script>

    
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3.4.1/dist/jquery.fancybox.min.css">

    
<script src="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3.4.1/dist/jquery.fancybox.min.js"></script>

    <script>
        let lazyloadT = Boolean('true'),
            auto_fancybox = Boolean('false')
        if (auto_fancybox) {
            $(".post__content").find('img').each(function () {
                var element = document.createElement("a");
                $(element).attr("data-fancybox", "gallery");
                $(element).attr("href", $(this).attr("src"));
                if (lazyloadT) {
                    $(element).attr("href", $(this).attr("data-srcset"));
                }
                $(this).wrap(element);
            });
        } else {
            $(".post__content").find("fancybox").find('img').each(function () {
                var element = document.createElement("a");
                $(element).attr("data-fancybox", "gallery");
                $(element).attr("href", $(this).attr("src"));
                if (lazyloadT) {
                    $(element).attr("href", $(this).attr("data-srcset"));
                }
                $(this).wrap(element);
            });
        }
    </script>
 

 

 

 

 


    

    
    
    
    <script>
        function loadComment() {
            let e;
            (e = document.createElement("script")).src = 'https://cdn.jsdelivr.net/npm/valine@1.4.14/dist/Valine.min.js',
            document.body.appendChild(e);
            e.onload = () => {
                var valineConfig = {"appId":"c21JqSBfScFdueO44Scwp9Ba-gzGzoHsz","appKey":"apETP0QIekHzRXjTHvOnrQmS","placeholder":null,"path":null,"avatar":"retro","meta":["nick","mail","link"],"pageSize":null,"lang":null,"visitor":null,"highlight":null,"avatarForce":null,"recordIP":null,"serverURLs":null,"enableQQ":true,"requiredFields":["nick","mail"],"emojiCDN":null,"emojiMaps":null};
                valineConfig.el = '#valine_container';
                for (var i in valineConfig) {
                    if (valineConfig[i] === null) delete valineConfig[i];
                }
                new Valine(valineConfig);
            };
        }
    
        var runningOnBrowser = typeof window !== "undefined";
        var isBot = runningOnBrowser && !("onscroll" in window) || typeof navigator !== "undefined" && /(gle|ing|ro|msn)bot|crawl|spider|yand|duckgo/i.test(navigator.userAgent);
        var supportsIntersectionObserver = runningOnBrowser && "IntersectionObserver" in window;
    
        setTimeout(function () {
            if (!isBot && supportsIntersectionObserver) {
                var comment_observer = new IntersectionObserver(function(entries) {
                    if (entries[0].isIntersecting) {
                        loadComment();
                        comment_observer.disconnect();
                    }
                }, { threshold: [0] });
                comment_observer.observe(document.getElementById('comment'));
            } else {
                loadComment();
            }
        }, 1);
    </script>


    
    
    
    
    

    
    
    
    
    

    
    
    



    </body>
</html>
